import 'dart:io';

import 'package:dio/dio.dart';
import 'package:easydubbing/utils/FutureDioToken.dart';
import 'package:easydubbing/utils/SpUtil.dart';
import 'package:easydubbing/utils/api.dart';
import 'package:easydubbing/utils/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tencentplayer/flutter_tencentplayer.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loading_indicator_view/loading_indicator_view.dart';
import 'package:path_provider/path_provider.dart';

class Preview extends StatefulWidget{
  final String url;

  const Preview({Key key, this.url}) : super(key: key);
  _PreviewState createState() => _PreviewState();
}
class _PreviewState extends State<Preview>{
  String url;
  TencentPlayerController player;
  bool isPlaying = false;
  TextEditingController title;
  TextEditingController desc;
  TextEditingController channel;
  File image;
  bool hasChosen = false;

  selectPic(state) async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      this.image = image;
      if(this.image!=null){
        hasChosen = true;
      }else{
        hasChosen = false;
      }
    });
    state(() {
    });
  }

  publish(){
    if(player.value.isPlaying)
      player.pause();
    if(SpUtil.sharedPreferences.getInt("uid")==null){
      showDialog(
          context: context,
          builder: (context){
            return AlertDialog(
              shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
              title: Text('提示'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    Text("请先登录！")
                  ],
                ),
              ),
              actions: <Widget>[
                TextButton(
                  child: Text('确定',style: TextStyle(color: Color(0xFFF16050)),),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            );
          }
      );
    }
    else{
      showDialog(
          context: context,
          builder: (context){
            return StatefulBuilder(builder: (context,state){
              return AlertDialog(
                shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                title: Text('输入发布信息'),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: <Widget>[
                      Row(
                        children: [
                          Text("标题："),
                          Expanded(child: TextField(
                            cursorColor: Color(0xFFBBBBBB),
                            cursorWidth: 1,
                            controller: title,
                            maxLines: 1,
                            style: TextStyle(color: Colors.black),
                            decoration: InputDecoration(
                              hintText: '请输入标题',
                              hintStyle: TextStyle(color: Color(0xFFbbbbbb)),
                              border: InputBorder.none,
                            ),
                          )),
                        ],
                      ),
                      Row(
                        children: [
                          Text("描述："),
                          Expanded(child: TextField(
                            cursorColor: Color(0xFFBBBBBB),
                            cursorWidth: 1,
                            controller: desc,
                            maxLines: 1,
                            style: TextStyle(color: Colors.black),
                            decoration: InputDecoration(
                              hintText: '请输入描述',
                              hintStyle: TextStyle(color: Color(0xFFbbbbbb)),
                              border: InputBorder.none,
                            ),
                          )),
                        ],
                      ),
                      Row(
                        children: [
                          Text("频道："),
                          Expanded(child: TextField(
                            cursorColor: Color(0xFFBBBBBB),
                            cursorWidth: 1,
                            controller: channel,
                            maxLines: 1,
                            style: TextStyle(color: Colors.black),
                            decoration: InputDecoration(
                              hintText: '请输入频道',
                              hintStyle: TextStyle(color: Color(0xFFbbbbbb)),
                              border: InputBorder.none,
                            ),
                          )),
                        ],
                      ),
                      InkWell(
                        onTap: ()=>selectPic(state),
                        child: Container(
                          height: 120,
                          decoration: BoxDecoration(
                              color: Colors.black12,
                              borderRadius: BorderRadius.all(Radius.circular(3))
                          ),
                          child: !hasChosen?Column(
                            children: [
                              Spacer(),
                              Icon(Icons.add_circle_rounded),
                              Text("选择封面",style: TextStyle(fontSize: 12),),
                              Spacer(),
                            ],
                          ):Image.file(image,),
                        ),
                      )
                    ],
                  ),
                ),
                actions: <Widget>[
                  TextButton(
                    child: Text('取消',style: TextStyle(color: Color(0xFFF16050)),),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                  TextButton(
                    child: Text('确定',style: TextStyle(color: ProjectColor.mainColor),),
                    onPressed: () async {
                      if(title.value.text==""||desc.value.text==""||channel.value.text==""
                          ||!hasChosen){
                        showDialog(
                            context: context,
                            builder: (context){
                              return AlertDialog(
                                shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                title: Text('提示'),
                                content: SingleChildScrollView(
                                  child: ListBody(
                                    children: <Widget>[
                                      Text("请填写完整！")
                                    ],
                                  ),
                                ),
                                actions: <Widget>[
                                  TextButton(
                                    child: Text('确定',style: TextStyle(color: Color(0xFFF16050)),),
                                    onPressed: () {
                                      Navigator.pop(context);
                                    },
                                  ),
                                ],
                              );
                            }
                        );
                        return;
                      }
                      var image = await MultipartFile.fromFile(
                        this.image.path,
                        filename: "video",
                      );
                      FormData formData = FormData.fromMap({"cover":image});
                      FutureDio("upload", Api.publishDirectly,{
                        "uid":SpUtil.sharedPreferences.getInt("uid"),
                        "title":title.value.text,
                        "desc":desc.value.text,
                        "channel":channel.value.text,
                        "videoPath":widget.url
                      },formData: formData).then((value) {
                        setState(() {
                          hasChosen = false;
                          this.image = null;
                        });
                        print(value);
                        Fluttertoast.showToast(
                            msg: '发布成功',
                            toastLength: Toast.LENGTH_SHORT,
                            gravity: ToastGravity.BOTTOM,
                            backgroundColor: Colors.black38,
                            textColor: Colors.white,
                            fontSize: 16.0
                        );
                        Navigator.pop(this.context);
                        Navigator.pop(this.context);
                      });
                      BuildContext buildContext = context;
                      showDialog(
                          context: buildContext,
                          barrierDismissible: false,
                          builder: (buildContext){
                            return AlertDialog(
                                shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                title: Text('提示'),
                                content: Container(
                                  height: 100,
                                  child: Column(
                                    children: [
                                      Container(
                                        width: 50,
                                        height: 50,
                                        child: Center(
                                          child: Container(
                                            width: 50,
                                            height: 50,
                                            child: LineSpinFadeLoaderIndicator(
                                              ballColor: ProjectColor.mainColor,
                                            ),
                                          ),
                                        ),
                                      ),
                                      SizedBox(height: 10,),
                                      Text("发布中，请耐心等待~")
                                    ],
                                  ),
                                )
                            );
                          }
                      );
                      Navigator.pop(context);
                    },
                  ),
                ],
              );
            });
          }
      );
    }
  }

  _saveVideo() async {
    var appDocDir = await getExternalStorageDirectory();
    String fileName ="/" + DateTime.now().toString().substring(0,19).replaceAll(" ", "").replaceAll(":", "").replaceAll("-", "")+".mp4";
    String savePath = appDocDir.path + fileName;
    BuildContext buildContext = context;
    showDialog(
        context: buildContext,
        barrierDismissible: false,
        builder: (buildContext){
          return AlertDialog(
              shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
              title: Text('提示'),
              content: Container(
                height: 100,
                child: Column(
                  children: [
                    Container(
                      width: 50,
                      height: 50,
                      child: Center(
                        child: Container(
                          width: 50,
                          height: 50,
                          child: LineSpinFadeLoaderIndicator(
                            ballColor: ProjectColor.mainColor,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 10,),
                    Text("保存中，请耐心等待~")
                  ],
                ),
              )
          );
        }
    );
    await Dio().download(url, savePath).then((value){
      Fluttertoast.showToast(
          msg: '视频已保存到'+savePath,
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.black38,
          textColor: Colors.white,
          fontSize: 16.0
      );
      Navigator.pop(buildContext);
    });
  }

  @override
  void initState() {
    url = widget.url??"";
    title = new TextEditingController();
    desc = new TextEditingController();
    channel = new TextEditingController();
    player = TencentPlayerController.network(url,playerConfig: PlayerConfig(autoPlay: false));
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: ExactAssetImage("assets/images/uploadBg.jpg"),
                fit: BoxFit.fitHeight
              )
            ),
          ),
          Container(
            height: 210,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(5)),
              color: Colors.black38,
            ),
            margin: EdgeInsets.only(left: 10,right: 10,top: 200),
            child: Stack(
              children: [
                Center(
                  child:
                  AspectRatio(
                    aspectRatio: player.value.initialized?player.value.aspectRatio:1.5,
                    child: TencentPlayer(
                        player
                    ),
                  ),
                ),
                !isPlaying?Container(
                  alignment: Alignment.center,
                  child: ClipOval(
                    child: Container(
                      height: 45,
                      width: 45,
                      color: Color(0x6f000000),
                      padding: EdgeInsets.only(left: 3),
                      child: Icon(Icons.play_arrow_rounded,size: 35,color: Colors.white,),
                    ),
                  ),
                ): SizedBox(),
              ],
            ),
          ),
          Container(
            height: 250,
            margin: EdgeInsets.only(left: 10,right: 10,top: 200),
            child: GestureDetector(
              onTap: (){
                print(player.value.initialized);
                if(!player.value.initialized){
                  player.initialize().then((value) {
                    setState(() {{
                      player.play();
                      isPlaying = true;
                    }
                    });
                  });
                  return;
                }
                if(player.value.isPlaying){
                  setState(() {
                    isPlaying = false;
                    player.pause();
                  });
                }
                else
                  setState(() {
                    isPlaying = true;
                    player.play();
                  });
              },
            ),
          ),
          Container(
            height: 40,
            margin: EdgeInsets.only(left:100,top: 500,right: 100),
            alignment: Alignment.center,
            child: Row(
              children: [
                Spacer(),
                InkWell(
                  onTap:() => _saveVideo(),
                  child:  Text("保存到手机",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
                ),
                Spacer(),
              ],
            ),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(20)),
                gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [
                      ProjectColor.deepColor,
                      ProjectColor.mainColor,
                    ]
                )),
          ),
          Container(
            height: 40,
            margin: EdgeInsets.only(left:100,top: 550,right: 100),
            alignment: Alignment.center,
            child: Row(
              children: [
                Spacer(),
                InkWell(
                  onTap:() => publish(),
                  child:  Text("发布到社区",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
                ),
                Spacer(),
              ],
            ),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(20)),
                gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [
                      ProjectColor.deepColor,
                      ProjectColor.mainColor,
                    ]
                )),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    player.dispose();
    super.dispose();
  }

}